<?php

namespace app\models;

use app\components\BaseActiveRecord;
use Yii;
use yii\db\Exception;

/**
 * This is the model class for table "{{%score}}".
 *
 * @property int $id
 * @property int $uid
 * @property int $book_id
 * @property int $score
 * @property int $create_time
 */
class UserScore extends BaseActiveRecord {
    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%user_score}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['uid', 'book_id', 'score', 'create_time'], 'integer'],
            [['score'], 'in', 'range' => [1, 2, 3, 4, 5]],

        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => Yii::t('app', 'ID'),
            'uid' => Yii::t('app', 'Uid'),
            'book_id' => Yii::t('app', 'Book ID'),
            'score' => Yii::t('app', 'Score'),
            'create_time' => Yii::t('app', 'Create Time'),
        ];
    }

    /**
     * @param $score
     * @param $book
     * @return array
     * @throws Exception
     */
    public static function saveScore($score, Book $book) {
        $uid = Yii::$app->user->id;
        if (!$uid) {
            return self::retErr('您还未登陆.');
        }

        if (self::find()->where("uid = {$uid} and book_id = {$book->id}")->one()) {
            return self::retErr('您已经评价过了!');
        }

        $model = new UserScore();
        $model->book_id = $book->id;
        $model->uid = $uid;
        $model->score = $score;
        $model->save();

        $book->score = self::getScore($book->id);
        $book->saveSuccessMessage = '评分成功';

        return $book->save();
    }

    public static function getScore($book_id) {
        $score = self::find()->where("book_id = {$book_id}")->sum('score');
        $users = self::find()->where("book_id = {$book_id}")->count();
        return round($score / $users * 2, 1);
    }

    public static function getUserScore($book_id) {
        $uid = Yii::$app->user->id;
        if (!$uid) {
            return 0;
        }
        $model = self::find()->where("uid = {$uid} and book_id = {$book_id}")->one();
        return $model ? $model['score'] : 0;
    }
}
